﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Extension;
using System;
namespace UnityEditor.Extension
{
    public static class GenericMenuExtension
    {
        public static GenericMenu InitForSubject(this GenericMenu gmenu, PropertyIndexer property,
            GenericMenu.MenuFunction2 OnSelect)
        {
            if(gmenu.isNotNull())
            {
                gmenu.AddItem(new GUIContent("NONE"), false, OnSelect, "NONE");
                gmenu.AddSeparator("");
                List<string> mlinks = GetLinks(property);
                mlinks.ForEach(m => gmenu.AddItem(new GUIContent(m), false, OnSelect, m));
            }
            return gmenu;
        }

        static List<Type> GetTypes(SerializedProperty property)
        {
            List<Type> types = new List<Type>();
            property.ForEachItem("", t =>
            {
                types.Add(TypeExtension.GetType(t.stringValue));
                return false;
            });
            return types;
        }

        static List<string> GetLinks(PropertyIndexer property)
        {
            List<Type> types = GetTypes(property["types"]);
            List<string> mlinks = new List<string>();
            SubjectiveScrollList scrollList = (property.target as MonoBehaviour).GetComponentInParent<SubjectiveScrollList>();

            if (property["content"].objectReferenceValue)
            {
                mlinks = property["content"].objectReferenceValue.MemberPathsInclusiveTypes(
               property["genericType"].boolValue, "", types.ToArray());
            }
            else if (scrollList)
            {
                object value = scrollList.subject.value;
                Type valueType = value.GetType();
                string typeName = valueType.ToString().GetStringBetween("[", "]");
                valueType = TypeExtension.GetType(typeName);
                mlinks = valueType.MemberPathsFromType(property["genericType"].boolValue,
                    "", types.ToArray());
            }
            
            return mlinks;
        }
    }
}
